using UnityEngine;
using System.Collections;

namespace EnemyStates
{
    public class Chasing : FSMBehaviour
    {
        /// <summary>
        /// A que distancia va a empezar a disparar.
        /// ej : 0.8 significa que va a acercarse hasta estar a 80% del rango del arma y ahi empieza a disparar.
        /// </summary>
        const float c_ShootingRangeFactor = 0.8f;
        /// <summary>
        /// Cuanto tiempo tarda en desaparecer
        /// </summary>
        const float c_LoseSightTimer = 3.0f;
        /// <summary>
        /// Cuando pasan a este estado tienen un tiempo de reaccion antes de hacer algo.
        /// </summary>
        const float c_ReactionDelay = 0.5f;
        bool m_IsOnShootingRange = false;
        Enemy m_Owner;
        Vector3 m_CurrenTargetPos;
        Vector3 m_PrevTargetPos;
        public bool LostSight = false;
        public float m_Timer = 0;
        float m_DelayTimer = 0.0f;
        public bool m_OutOfDelay = false;
        public Chasing(Enemy owner)
        {
            this.m_Owner = owner;
        }
        public override void Update()
        {
            base.Update();

            m_PrevTargetPos = m_CurrenTargetPos;
            m_CurrenTargetPos = m_Owner.m_TargetedCharacter.transform.position;
            LostSight = !(m_Owner.IsCharacterInSight());
            if (LostSight)
            {
                m_Timer += Time.deltaTime;
                if (m_Timer >= c_LoseSightTimer)
                {
                    m_Owner.OnLostSight(m_CurrenTargetPos, (m_CurrenTargetPos - m_PrevTargetPos).normalized);
                    m_Owner.SendEvent(ENEMYEVENTS.LOSTSIGHT);
                    return;
                }
            }
            else
            {
                m_Timer = 0;
            }
            if (m_DelayTimer < c_ReactionDelay)
            {
                m_DelayTimer += Time.deltaTime;
                if (m_DelayTimer >= c_ReactionDelay)
                {
                    m_OutOfDelay = true;
                }
            }


            if (m_Owner.m_TargetedCharacter.IsAlive())
            {
                if (!m_IsOnShootingRange || LostSight)
                    m_Owner.MoveTo(m_Owner.m_TargetedCharacter.transform.position);
                //m_Owner.transform.LookAt(m_Owner.m_TargetedCharacter.transform.position);
                m_Owner.m_EyeDirection = (m_Owner.m_TargetedCharacter.transform.position - m_Owner.transform.position).normalized;
                //m_Owner.UpdateEyeDirection();


                //Cuando el enemigo llega a cierto rango (dictado por el ShootingRangefactor
                //Ahi empieza a disparar y recien cuando se aleja del rango total del arma deja de disparar.
                float distance = Vector3.Distance(m_Owner.transform.position,
                        m_Owner.m_TargetedCharacter.transform.position);

                if (LostSight == false)
                {
                    if (m_IsOnShootingRange)
                    {
                        //si estoy a mas distancia de lo que tira el arma deja de estar en rango de disparar.
                        if (distance > m_Owner.GetEquippableRange())
                        {
                            m_IsOnShootingRange = false;
                        }
                    }
                    else
                    {
                        //si estoy a la distancia deseada para disparar
                        if (distance < m_Owner.GetEquippableRange() * c_ShootingRangeFactor)
                        {
                            m_IsOnShootingRange = true;
                            m_Owner.StopMoving();
                        }
                    }
                }
                if (m_IsOnShootingRange)
                {
                    if(m_OutOfDelay)
                    StartShooting();
                }
            }
        }
        public override void OnEnable()
        {
            m_OutOfDelay = false;
            m_DelayTimer = 0;
            m_Owner.m_CurrentEyeRotation = 0;
            m_Timer = 0;
            m_CurrenTargetPos = m_Owner.m_TargetedCharacter.transform.position;
            m_PrevTargetPos = m_CurrenTargetPos;
            LostSight = false;
        }
        public override void OnDisable()
        {
            m_IsOnShootingRange = false;

        }
        void StartShooting()
        {
            float r = Random.Range(0.0f, 1.0f);

            Character target = m_Owner.m_TargetedCharacter;
            float missOffset = 3;
            float hitChance = GameManager.GetInstance().m_EnemyAcurracy;
            if (target.m_Moving) //si esta moviendo tiene menos chance de pegar
            {
                hitChance -= GameManager.GetInstance().m_MovingAimReduction;
                if (target.m_Sprinting) //si esta corriendo tiene aun menos
                {
                    hitChance -= GameManager.GetInstance().m_SprintingAimReduction;
                }
            }
            if (r <= hitChance)
            {
                m_Owner.UseEquippable(target);
            }
            else
            {
                int missDirection = Random.Range(0, 2);
                if (missDirection == 0) missDirection = -1;

                m_Owner.UseEquippable(target.transform.position- Vector3.up - m_Owner.transform.forward * missOffset + m_Owner.transform.right * missDirection*3);
                //Debug.Log("Enemigo misseo un tiro");
            }
            //Debug.Log(random);
        }
    }
}
